package main

import (
	"fmt"
	"net"
	"strconv"
	"strings"
)

// ipToBinary 将IP地址转换为二进制字符串
func ipToBinary(ipStr string) (string, error) {
	ip := net.ParseIP(ipStr)
	if ip == nil {
		return "", fmt.Errorf("无效的IP地址")
	}

	var binaryStr string
	if ip.To4() != nil {
		// IPv4地址
		ipBytes := ip.To4()
		for _, b := range ipBytes {
			binaryStr += fmt.Sprintf("%08b", b)
		}
	} else if ip.To16() != nil {
		// 将IPv6地址转换为字符串数组，每个部分16位
		ipString := strings.Split(ip.String(), ":")

		// 将每个十六进制部分转换为二进制字符串
		for _, part := range ipString {
			bin, err := strconv.ParseUint(part, 16, 64)
			if err != nil {
				return "", err
			}
			binaryStr += fmt.Sprintf("%016b", bin)
		}

	} else {
		return "", fmt.Errorf("未知的IP地址类型")
	}

	return binaryStr, nil
}

func main() {
	ipv4Str := "192.168.1.1"
	ipv6Str := "5000:3a3a:3a3a:0:6feb:a4d7:ce5d:2"

	ipv4Binary, err := ipToBinary(ipv4Str)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("IPv4地址的二进制形式: %s\n", ipv4Binary)

	ipv6Binary, err := ipToBinary(ipv6Str)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("IPv6地址的二进制形式: %s\n", ipv6Binary)
}

func ipv6ToBinary(ipv6 string) (string, error) {
	// 解析IPv6地址
	ip := net.ParseIP(ipv6)
	if ip == nil {
		return "", fmt.Errorf("invalid IPv6 address: %s", ipv6)
	}

	// 确保是IPv6地址
	if ip.To16() == nil {
		return "", fmt.Errorf("not a valid IPv6 address: %s", ipv6)
	}

	// 将IPv6地址转换为字符串数组，每个部分16位
	ipString := strings.Split(ip.String(), ":")

	// 将每个十六进制部分转换为二进制字符串
	var binaryParts []string
	for _, part := range ipString {
		bin, err := strconv.ParseUint(part, 16, 64)
		if err != nil {
			return "", err
		}
		binStr := fmt.Sprintf("%016b", bin)
		binaryParts = append(binaryParts, binStr)
	}

	// 将所有部分连接起来
	return strings.Join(binaryParts, ""), nil
}

func main22() {
	ipv6 := "5000:3a3a:3a3a:0:6feb:a4d7:ce5d:2"
	binaryStr, err := ipv6ToBinary(ipv6)
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Binary representation:", binaryStr)
	}
}
